package com.jewaton.auth.commons.action;

import com.jewaton.auth.commons.operationlog.LogValueStack;
import com.jewaton.auth.commons.operationlog.service.OperatelogService;
import com.jewaton.auth.commons.service.DistrictService;
import com.jewaton.auth.commons.util.DistrictList;
import com.jewaton.auth.commons.util.DistrictListOnweb;
import com.jewaton.auth.commons.util.DistrictMapValue;
import com.jewaton.auth.commons.util.Pager;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 基础的ACTION,提供一些公共功能方法
 */
public class BaseAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {

	protected static final Log logger = LogFactory.getLog(BaseAction.class);
	/**
	 * 会话对象
	 */
	protected Map session;
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected LogValueStack logValueStack = LogValueStack.getContext();
	
	/**
	 * 分页对象
	 */
	public Pager pager = new Pager();
	
	public BaseAction() {
	}
	
	@Resource(name = "operatelogService")
	protected OperatelogService operatelogService;
	

	@Resource(name = "districtService")
	private DistrictService districtService;
	
	private DistrictListOnweb districtListOnweb;
	
	private DistrictList districtList;
	private DistrictMapValue districtMapValue;


	public Map getSession() {
		return session;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
		
	}
	public Pager getPager() {
		return pager;
	}

	public void setPager(Pager pager) {
		this.pager = pager;
	}
    public OperatelogService getOperatelogService() {
		return operatelogService;
	}

	public void setOperatelogService(OperatelogService operatelogService) {
		this.operatelogService = operatelogService;
	}
	
	protected void writeJSON(String json) throws IOException {
		if(isIE()) {
			response.setContentType("text/html");
		}else {
			response.setContentType("application/json");
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.write(json);
		writer.flush();
		writer.close();
	}
	
	protected void writeJSON(Object data, JsonConfig config) throws IOException {
		String json = JSONObject.fromObject(data, config).toString();
		writeJSON(json);
	}
	
	protected void writeJSONArray(Object data, JsonConfig config) throws IOException {
		String json = JSONArray.fromObject(data, config).toString();
		writeJSON(json);
	}
	
	protected String getUserAgent() {
		return request.getHeader("user-agent");
	}
	
	protected boolean isIE() {
		String userAgent = getUserAgent();
		return userAgent.toLowerCase().contains("msie");
	}

    
	public String getIpAddr() {
	       String ip = request.getHeader("x-forwarded-for");
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getHeader("Proxy-Client-IP");
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getHeader("WL-Proxy-Client-IP");
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getRemoteAddr();
	       }
	       return ip;
	   }
	
	protected boolean isGet() {
		return request.getMethod().equalsIgnoreCase("GET");
	}
	
	protected boolean isPost() {
		return request.getMethod().equalsIgnoreCase("POST");
	}
	
	public void keepLink(){
		Long time = System.currentTimeMillis();
	}
	
	@Override
	public void validate() {
		if(isPost()){
			super.validate();
			if(super.hasFieldErrors()){
				Map<String, List<String>> errors = super.getFieldErrors();
				request.setAttribute("validErrors", errors);
			}
		}else{
			request.setAttribute("validErrors", new ArrayList<String>(0));
			super.clearFieldErrors();
		}
	}

    protected Cookie getCookie(String name) {
        try{
            Cookie cookies[] = request.getCookies();
            if (cookies == null || name == null || name.length() == 0) {
                return null;
            }
            for (int i = 0; i < cookies.length; i++) {
                if (name.equals(cookies[i].getName())) {
                    return cookies[i];
                }
            }
            return null;
        } catch (Exception e){
            return null;
        }
    }

    protected void deleteCookie(Cookie cookie, String path) {
        try{
            if (cookie != null) {
                if(path==null)
                    path=getPath();
                cookie.setPath(path);
                cookie.setValue("");
                cookie.setMaxAge(0);
                //cookie.setDomain(request.getServerName());
                response.addCookie(cookie);
            }
        }catch (Exception e){ }
    }

    protected void setCookie( String name, String value, int maxAge, String path) {
        try{
            Cookie cookie = new Cookie(name, value == null ? "" : value);
            cookie.setMaxAge(maxAge);
            if(path==null)
                path=getPath();
            cookie.setPath(path);
            //cookie.setDomain(request.getServerName());
            response.addCookie(cookie);
        }catch (Exception e){ }
    }

    protected String getPath() {
        String path = request.getContextPath();
        return (path == null || path.length() == 0) ? "/" : path;
    }
	
	public DistrictMapValue getDistrictMapValue() {
		return districtMapValue;
	}

	public void setDistrictMapValue(DistrictMapValue districtMapValue) {
		this.districtMapValue = districtMapValue;
	}

	public DistrictService getDistrictService() {
		return districtService;
	}

	public void setDistrictService(DistrictService districtService) {
		this.districtService = districtService;
		districtMapValue = new DistrictMapValue(getDistrictService());
		districtList = new DistrictList(getDistrictService());
		districtListOnweb = new DistrictListOnweb(getDistrictService());
	}

	public DistrictListOnweb getDistrictListOnweb() {
		return districtListOnweb;
	}

	public void setDistrictListOnweb(DistrictListOnweb districtListOnweb) {
		this.districtListOnweb = districtListOnweb;
	}

	public DistrictList getDistrictList() {
		return districtList;
	}

	public void setDistrictList(DistrictList districtList) {
		this.districtList = districtList;
	}

}
